<template>
  <div class="financial-reconciliation-container">
    <!-- 左侧树形结构区域 -->
    <div class="left-tree-panel">
      <div class="tree-header">
        <h4>
          <i class="el-icon-office-building"></i>
          楼栋用房分类
        </h4>
      </div>
      <div class="tree-search">
        <el-input 
          v-model="treeSearchText" 
          placeholder="请输入楼栋内容" 
          size="small" 
          clearable>
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
      </div>
      <div class="tree-container">
        <el-tree
          :data="treeData"
          :props="treeProps"
          :filter-node-method="filterNode"
          ref="tree"
          node-key="id"
          :expand-on-click-node="false"
          :default-expand-all="true"
          :highlight-current="true"
          @node-click="handleNodeClick"
          class="custom-tree">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span class="tree-node-label">
              <i :class="getNodeIcon(data)" class="tree-node-icon"></i>
              {{ node.label }}
            </span>
          </span>
        </el-tree>
      </div>
    </div>

    <!-- 右侧内容区域 -->
    <div class="right-content-panel">
      <div class="financial-reconciliation">
        <!-- Tab切换 -->
        <div class="tab-container">
          <el-tabs v-model="activeTab" @tab-click="handleTabClick" class="custom-tabs">
            <el-tab-pane label="月对账" name="monthly">
              <template slot="label">
                <span class="tab-label">
                  <i class="el-icon-date"></i>
                  月对账
                </span>
              </template>
            </el-tab-pane>
            <el-tab-pane label="日对账" name="daily">
              <template slot="label">
                <span class="tab-label">
                  <i class="el-icon-time"></i>
                  日对账
                </span>
              </template>
            </el-tab-pane>
          </el-tabs>
        </div>
        <!-- 搜索筛选区 -->
        <div class="filter-container">
          <el-form :inline="true" :model="filterForm" class="filter-form">
            <el-form-item label="时间:">
              <el-date-picker
                v-model="filterForm.dateRange"
                type="daterange"
                range-separator="—"
                start-placeholder="2025-01"
                end-placeholder="2025-07"
                value-format="yyyy-MM-dd"
                class="date-picker"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="审核状态:">
              <el-select 
                v-model="filterForm.auditStatus" 
                placeholder="全部"
                clearable
                class="filter-select"
              >
                <el-option label="全部" value=""></el-option>
                <el-option label="已审核" value="audited"></el-option>
                <el-option label="未审核" value="unaudited"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="searchData">查询</el-button>
              <el-button icon="el-icon-refresh" @click="resetFilter">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <!-- 操作按钮区 -->
        <div class="action-container">
          <div class="action-buttons">
            <el-button type="success" icon="el-icon-download" @click="exportData">导出</el-button>
            <el-button type="warning" icon="el-icon-upload2" @click="batchImport">批量导入</el-button>
            <el-button type="info" icon="el-icon-view" @click="viewDetails">查看详情</el-button>
          </div>
        </div>
        <!-- 数据表格 -->
        <div class="table-container">
          <div class="table-header">
            <div class="table-title">
              <i class="el-icon-tickets"></i>
              对账列表
            </div>
            <div class="table-info">
              共 {{ tableData.length }} 条数据
            </div>
          </div>
          <el-table 
            :data="tableData" 
            border 
            stripe
            style="width: 100%"
            :header-cell-style="headerCellStyle"
            class="custom-table"
            v-loading="loading"
            element-loading-text="加载中..."
          >
            <el-table-column prop="roomNumber" label="序号" width="80" align="center"></el-table-column>
            <el-table-column prop="period" label="时间" width="100" align="center"></el-table-column>
            <el-table-column prop="totalConsumption" label="交易总数量" width="120" align="center"></el-table-column>
            <el-table-column prop="currentReading" label="账务" width="80" align="center">
              <template slot-scope="scope">
                <span class="reading-value">{{ scope.row.currentReading }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="previousReading" label="积分对账" width="100" align="center">
              <template slot-scope="scope">
                <span class="reading-value">{{ scope.row.previousReading }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="consumption" label="缴费对账" width="100" align="center">
              <template slot-scope="scope">
                <span class="reading-value">{{ scope.row.consumption }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="unitPrice" label="支付宝对账" width="120" align="center">
              <template slot-scope="scope">
                <span class="reading-value">{{ scope.row.unitPrice }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="currentAmount" label="现金对账" width="100" align="center">
              <template slot-scope="scope">
                <span class="reading-value">{{ scope.row.currentAmount }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="previousAmount" label="消费金额(元)" width="120" align="center">
              <template slot-scope="scope">
                <span class="amount-value">{{ scope.row.previousAmount }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="totalAmount" label="补助金额" width="100" align="center">
              <template slot-scope="scope">
                <span class="amount-value">{{ scope.row.totalAmount }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="subsidyAmount" label="期初补贴金额" width="120" align="center">
              <template slot-scope="scope">
                <span class="amount-value">{{ scope.row.subsidyAmount }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="finalAmount" label="合计金额" width="100" align="center">
              <template slot-scope="scope">
                <span class="amount-value total-amount">{{ scope.row.finalAmount }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="auditStatus" label="审核状态" width="100" align="center">
              <template slot-scope="scope">
                <el-tag 
                  size="small" 
                  :type="scope.row.auditStatus === '未审核' ? 'warning' : scope.row.auditStatus === '已审核' ? 'success' : 'info'"
                >
                  {{ scope.row.auditStatus }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right" align="center">
              <template slot-scope="scope">
                <div class="action-buttons">
                  <el-button 
                    type="primary" 
                    size="mini" 
                    icon="el-icon-view"
                    @click="viewRecord(scope.row)"
                  >
                    明细
                  </el-button>
                  <el-button 
                    type="success" 
                    size="mini" 
                    icon="el-icon-check"
                    @click="auditRecord(scope.row)"
                    :disabled="scope.row.auditStatus === '已审核'"
                  >
                    标记完成
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <!-- 底部统计 -->
          <div class="table-footer">
            <div class="summary-info">
              <span class="summary-item">
                <strong>合计: {{ totalSummary.total }}</strong>
              </span>
              <span class="summary-item">
                <strong>{{ totalSummary.detail }}</strong>
              </span>
            </div>
          </div>
        </div>
        <!-- 明细弹窗 -->
        <el-dialog
          title="对账明细"
          :visible.sync="showDetailDialog"
          width="80%"
          class="custom-dialog"
          :close-on-click-modal="false"
        >
          <div class="detail-content">
            <div class="detail-header">
              <h3>{{ selectedRecord ? `${selectedRecord.roomNumber}号 - ${selectedRecord.period}` : '' }}</h3>
              <div class="detail-info">
                <span>审核状态: </span>
                <el-tag 
                  size="small" 
                  :type="selectedRecord && selectedRecord.auditStatus === '已审核' ? 'success' : 'warning'"
                >
                  {{ selectedRecord ? selectedRecord.auditStatus : '' }}
                </el-tag>
              </div>
            </div>
            <el-table 
              :data="detailData" 
              border 
              stripe
              style="width: 100%"
              class="detail-table"
            >
              <el-table-column prop="date" label="日期" width="120" align="center"></el-table-column>
              <el-table-column prop="type" label="类型" width="100" align="center"></el-table-column>
              <el-table-column prop="amount" label="金额" width="100" align="center">
                <template slot-scope="scope">
                  <span :class="scope.row.amount > 0 ? 'positive-amount' : 'negative-amount'">
                    {{ scope.row.amount }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="balance" label="余额" width="100" align="center"></el-table-column>
              <el-table-column prop="operator" label="操作员" width="100" align="center"></el-table-column>
              <el-table-column prop="remark" label="备注" align="center"></el-table-column>
            </el-table>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="showDetailDialog = false">关闭</el-button>
            <el-button 
              type="primary" 
              @click="confirmAudit"
              v-if="selectedRecord && selectedRecord.auditStatus === '未审核'"
            >
              确认审核
            </el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script>
import financialReconciliationMock from '@/api/mock/financialReconciliation'
export default {
  name: 'FinancialReconciliation',
  data() {
    return {
      // 树形结构相关
      treeSearchText: '',
      treeData: [],
      selectedNode: null,
      treeProps: {
        children: 'children',
        label: 'label'
      },
      activeTab: 'monthly',
      loading: false,
      tableData: [],
      totalSummary: {
        total: '123,121',
        detail: '123,121 123,121 123,121 123,121 123,121 123,121 123,121 123,121 123,121 123,121'
      },
      filterForm: {
        dateRange: ['2025-01-01', '2025-07-31'],
        auditStatus: ''
      },
      showDetailDialog: false,
      selectedRecord: null,
      detailData: [],
      headerCellStyle: {
        backgroundColor: '#f8f9fa',
        color: '#495057',
        fontWeight: 'bold',
        textAlign: 'center'
      }
    }
  },
  watch: {
    treeSearchText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    this.loadTreeData()
    this.loadData()
  },
  methods: {
    // 加载树形结构数据 - 使用mock数据
    loadTreeData() {
      // 直接使用mock数据，避免API请求
      this.treeData = [
        {
          id: 1,
          label: '楼栋用房分类',
          children: [
            {
              id: 2,
              label: '宿舍',
              children: [
                {
                  id: 3,
                  label: 'A栋',
                  children: [
                    { id: 4, label: '101', roomId: 101, buildingId: 3 },
                    { id: 5, label: '102', roomId: 102, buildingId: 3 },
                    { id: 6, label: '103', roomId: 103, buildingId: 3 },
                    { id: 7, label: '104', roomId: 104, buildingId: 3 }
                  ]
                }
              ]
            },
            {
              id: 8,
              label: '二层',
              children: [
                {
                  id: 9,
                  label: 'B栋',
                  children: [
                    { id: 10, label: '201', roomId: 201, buildingId: 9 },
                    { id: 11, label: '202', roomId: 202, buildingId: 9 },
                    { id: 12, label: '203', roomId: 203, buildingId: 9 }
                  ]
                }
              ]
            }
          ]
        }
      ]
    },
    
    // 树形结构过滤方法
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    
    // 树形节点点击事件
    handleNodeClick(data) {
      console.log('选中节点:', data)
      this.selectedNode = data
      // 根据选中的节点过滤表格数据
      this.loadData()
    },
    
    // 获取节点图标
    getNodeIcon(data) {
      if (data.roomId) {
        return 'el-icon-house'
      } else if (data.buildingId) {
        return 'el-icon-office-building'
      } else if (data.children && data.children.length > 0) {
        return 'el-icon-folder-opened'
      } else {
        return 'el-icon-folder'
      }
    },
    loadData() {
      this.loading = true
      setTimeout(() => {
        let response = financialReconciliationMock
        let filteredData = response.msg.list

        // 根据选中的树节点过滤数据
        if (this.selectedNode && this.selectedNode.roomId) {
          filteredData = filteredData.filter(item => 
            item.roomNumber === this.selectedNode.label
          )
        }

        // Apply filterForm filters
        if (this.filterForm.dateRange && this.filterForm.dateRange.length === 2) {
          const startDate = new Date(this.filterForm.dateRange[0])
          const endDate = new Date(this.filterForm.dateRange[1])
          filteredData = filteredData.filter(item => {
            const itemDate = new Date(item.period + '-01') // Assuming period is 'YYYY-MM'
            return itemDate >= startDate && itemDate <= endDate
          })
        }
        if (this.filterForm.auditStatus) {
          filteredData = filteredData.filter(item => item.auditStatus === (this.filterForm.auditStatus === 'audited' ? '已审核' : '未审核'))
        }

        this.tableData = filteredData
        this.totalSummary = response.msg.summary // Keep original summary for now, or calculate based on filtered data
        this.loading = false
      }, 500)
    },
    handleTabClick(tab) {
      console.log('切换到:', tab.name)
      this.loadData()
    },
    searchData() {
      this.loadData()
    },
    resetFilter() {
      this.filterForm = {
        dateRange: ['2025-01-01', '2025-07-31'],
        auditStatus: ''
      }
      this.selectedNode = null
      this.$refs.tree.setCurrentKey(null)
      this.loadData()
    },
    exportData() {
      this.$message.success('导出数据功能')
    },
    batchImport() {
      this.$message.success('批量导入功能')
    },
    viewDetails() {
      this.$message.success('查看详情功能')
    },
    viewRecord(row) {
      this.selectedRecord = row
      this.detailData = [
        {
          date: '2025-04-01',
          type: '充值',
          amount: 179,
          balance: 179,
          operator: 'admin',
          remark: '现金充值'
        },
        {
          date: '2025-04-02',
          type: '消费',
          amount: -50,
          balance: 129,
          operator: 'system',
          remark: '电费扣除'
        },
        {
          date: '2025-04-03',
          type: '充值',
          amount: 100,
          balance: 229,
          operator: 'admin',
          remark: '支付宝充值'
        }
      ]
      this.showDetailDialog = true
    },
    confirmAudit() {
      if (this.selectedRecord) {
        this.$confirm(`确认标记 ${this.selectedRecord.roomNumber}号 - ${this.selectedRecord.period} 为已审核吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.selectedRecord.auditStatus = '已审核'
          this.$message.success('标记完成!')
          this.showDetailDialog = false
          this.loadData() // 刷新数据
        }).catch(() => {
          this.$message.info('已取消操作')
        })
      }
    }
  }
}
</script>
<style scoped>
/* 主容器样式 */
.financial-reconciliation-container {
  display: flex;
  height: calc(100vh - 120px); /* 减去头部和底部的高度 */
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

/* 左侧树形结构面板 */
.left-tree-panel {
  width: 300px;
  background: white;
  border-radius: 12px 0 0 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  margin: 24px 0 24px 24px;
}

.tree-header {
  padding: 20px 20px 0;
  border-bottom: 1px solid #e9ecef;
}

.tree-header h4 {
  margin: 0 0 20px 0;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.tree-header h4 i {
  color: #3498db;
  font-size: 18px;
}

.tree-search {
  padding: 20px;
  border-bottom: 1px solid #e9ecef;
}

.tree-container {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.custom-tree {
  background: transparent;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 14px;
  padding-right: 8px;
}

.tree-node-label {
  display: flex;
  align-items: center;
  gap: 8px;
}

.tree-node-icon {
  color: #3498db;
  font-size: 16px;
}

/* 右侧内容面板 */
.right-content-panel {
  flex: 1;
  background: white;
  border-radius: 0 12px 12px 0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  margin: 24px 24px 24px 0;
  padding: 24px;
}

/* Tab切换 */
.tab-container {
  margin-bottom: 20px;
}

.custom-tabs .el-tabs__header {
  margin-bottom: 0;
}

.custom-tabs .el-tabs__nav-wrap::after {
  height: 0;
}

.tab-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

/* 搜索筛选区 */
.filter-container {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.filter-form .el-form-item {
  margin-bottom: 10px;
  margin-right: 20px;
}

.filter-input,
.filter-select,
.date-picker {
  width: 180px;
}

/* 操作按钮区 */
.action-container {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

/* 数据表格 */
.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.table-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  display: flex;
  align-items: center;
  gap: 8px;
}

.table-title i {
  color: #409eff;
}

.table-info {
  font-size: 14px;
  color: #606266;
}

.custom-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 操作按钮组 */
.custom-table .action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 5px; /* 按钮之间的间距 */
  justify-content: center; /* 居中显示 */
}

.reading-value,
.amount-value {
  font-weight: bold;
}

.positive-amount {
  color: #67c23a;
}

.negative-amount {
  color: #f56c6c;
}

.total-amount {
  color: #409eff;
}

/* 弹窗样式 */
.custom-dialog .el-dialog__header {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  padding: 20px;
}

.custom-dialog .el-dialog__title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.detail-content {
  padding: 20px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.detail-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.detail-info span {
  font-size: 14px;
  color: #606266;
  margin-right: 10px;
}

.detail-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.dialog-footer {
  padding: 20px;
  text-align: right;
  border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .financial-reconciliation-container {
    flex-direction: column;
    height: auto;
  }

  .left-tree-panel {
    width: auto;
    margin: 10px;
    border-radius: 12px;
  }

  .right-content-panel {
    margin: 10px;
    border-radius: 12px;
    padding: 15px;
  }

  .filter-form {
    flex-direction: column;
    align-items: flex-start;
  }

  .filter-form .el-form-item {
    margin-right: 0;
    width: 100%;
  }

  .filter-input,
  .filter-select,
  .date-picker {
    width: 100%;
  }

  .action-buttons {
    flex-direction: column;
  }

  .action-buttons .el-button {
    width: 100%;
  }
}
</style>


